<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>

    <script>
      function sleep(duration) {
        let start = Date.now();
        while (start + duration > Date.now()) {}
      }
      // 工作的任务
      const works = [
        () => {
          console.log("第1个任务开始");
          // sleep(0);
          sleep(20);
          console.log("第1个任务结束");
        },
        () => {
          console.log("第2个任务开始");
          sleep(0);
          // sleep(20);
          console.log("第2个任务结束");
        },
        () => {
          console.log("第3个任务开始");
          sleep(0);
          // sleep(20);
          console.log("第3个任务结束");
        },
      ];

      requestIdleCallback(workLoop, { timeout: 1000 });

      function workLoop(deadline) {
        console.log("本帧剩余时间：", parseInt(deadline.timeRemaining()));
        while (
          (deadline.timeRemaining() > 1 || deadline.didTimeout) &&
          works.length > 0
        ) {
          performUnitOfWork();
        }

        if (works.length > 0) {
          console.log(
            `只剩下${parseInt(
              deadline.timeRemaining()
            )}ms, 时间片到了，等待下次空闲时间的调度`
          );
          requestIdleCallback(workLoop);
        }
      }
      function performUnitOfWork() {
        // 取出工作的任务
        const task = works.shift();
        task(); // 执行任务
      }
    </script>
  </body>
</html>
